<?php
namespace app\common\service\WebSocket\SocketService; 

use app\Normal;
use app\BaseService;
use app\model\BbcModel\StoreMember;
use app\model\BbcModel\Order;
use app\model\BbcModel\VipOrder;
use app\common\service\StoreService\VipService;
use app\common\service\UserService\MemberService;

class MemberSocketService extends BaseService
{
    public $socket_connector;

    public $fd;

    public $host;
    public $pageLimit      = 2000;
    
    public function memberListExport($parameters = []) {        
        ini_set('memory_limit', '3096M');
        $this->socket_connector = $parameters['socket'];
        $this->fd               = $parameters['fd'];
        $this->host             = $parameters['host'];
        $data                   = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        if(isset($data['cb_id'])&&$data['cb_id']>0){
            $data['cb_id']=$data['cb_id'];
        }elseif($parameters['_master_user']['cb_id']>0){
            $data['cb_id']= $parameters['_master_user']['cb_id'];
        }
        $check=callApi(MemberService::class, 'makeWhere',$data);
        $where=$check['where'];
        $service=$check['service'];
        $business=$check['business'];
        $store=$check['store'];
        $fields="m.mid,m.mobile,s.id,s.sp_id,s.cb_id,s.mn_sid,s.cd,s.pay_time,s.vip_expired,s.nick_name";
        $total_count=StoreMember::instance()->alias('s')
            ->leftjoin('member m','m.mid=s.mid')
            ->where($where)
            ->count();
        $total_page  = ceil($total_count / $this->pageLimit);
        $importData  = [];
        $time=time();
        for ($page = 0; $page < $total_page; $page++) {
            $list=StoreMember::instance()->alias('s')
                ->field($fields)
                ->leftjoin('member m','m.mid=s.mid')
                ->where($where)
                ->order('s.id desc')
                ->limit($page * $this->pageLimit, $this->pageLimit)
                ->select()
                ->toArray();
            if ($list) {
                $tmpData = [];
                foreach ($list as $v) {
                    $orderList=Order::instance()->lists(['mid'=>$v['mid'],'mn_sid'=>$v['mn_sid'],'pay_status'=>1,'_fields_'=>'price_order']);
                    $order_num=count($orderList);
                    $order_price=array_sum(array_column($orderList,'price_order'));
                    $tmpData[] = [
                        $v['id'],
                        $v['mid'],
                        $store[$v['mn_sid']],
                        $business[$v['cb_id']],
                        $service[$v['sp_id']],
                        $v['mobile'],
                        $v['nick_name'],
                        $v['vip_expired']>$time?'会员':'普通用户',
                        date('Y-m-d H:i:s',$v['cd']),
                        $order_num,
                        $order_price,
                        $v['vip_expired']>0?date('Y-m-d H:i:s',$v['vip_expired']):'',
                        $v['pay_time']>0?date('Y-m-d H:i:s',$v['pay_time']):''
                        
                    ];
                }
                $importData = array_merge($importData, $tmpData);
            }

            if ($page == $total_page - 1) {
                $percent = 98.00; //预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }

            if ($this->socket_connector) {
                $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
                    'percent' => $percent,
                ]);
                $send = json_encode($send, JSON_UNESCAPED_UNICODE);
                $this->socket_connector->push($this->fd, $send);
            }
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00,
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->socket_connector->push($this->fd, $send);

        $fileName     = "会员列表导出";
        $headArr      = $this->getColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url,
            'name'=>'会员列表导出'
        ]);
    }
     //excel头部
    public function getColumns() {
        return [
            'ID编号',
            'MID',
            '店铺',
            '所属渠道',
            '所属服务商',
            '账号',
            '昵称',
            '类型',
            '注册时间',
            '订单数量',
            '订单金额',
            '会员到期时间',
            '最近购物时间'
        ];
    }
    
    
    
    
    public function vipListExport($parameters = []) {        
        ini_set('memory_limit', '3096M');
        $this->socket_connector = $parameters['socket'];
        $this->fd               = $parameters['fd'];
        $this->host             = $parameters['host'];
        $data                   = $parameters['requestData'];
        $data['cid']            = $parameters['_master_user']['cid'];
        if(isset($data['cb_id'])&&$data['cb_id']>0){
            $data['cb_id']=$data['cb_id'];
        }elseif($parameters['_master_user']['cb_id']>0){
            $data['cb_id']= $parameters['_master_user']['cb_id'];
        }
        $check=callApi(VipService::class, 'makeWhere',$data);
        $where=$check['where'];
        $service=$check['service'];
        $business=$check['business'];
        $store=$check['store'];
        $total_count=VipOrder::instance()
            ->where($where)
            ->count();
        $total_page  = ceil($total_count / $this->pageLimit);
        $importData  = [];
        $time=time();
        for ($page = 0; $page < $total_page; $page++) {
            $list=VipOrder::instance()
                ->where($where)
                ->limit($page * $this->pageLimit, $this->pageLimit)
                ->select()
                ->toArray();
            if ($list) {
                $tmpData = [];
                foreach ($list as $v) {
                    $tmpData[] = [
                        $store[$v['mn_sid']],
                        $v['mobile'],
                        $v['days'],
                        $v['amount'],
                        VipOrder::instance()->type[$v['type']],
                        $v['pay_time']>0?date('Y-m-d H:i:s',$v['pay_time']):'',
                        $v['sn'],
                        $v['pay_serial']
                    ];
                }
                $importData = array_merge($importData, $tmpData);
            }

            if ($page == $total_page - 1) {
                $percent = 98.00; //预留给写文件使用
            } else {
                $percent = bcdiv($page, $total_page - 1, 4);
                $percent = bcmul($percent, 100, 2);
            }

            if ($this->socket_connector) {
                $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
                    'percent' => $percent,
                ]);
                $send = json_encode($send, JSON_UNESCAPED_UNICODE);
                $this->socket_connector->push($this->fd, $send);
            }
        }
        //数据准备完成开始写入excel本地数据
        $send = Normal::returnWsStatus(Normal::WS_START, "进行中", [
            'percent' => 99.00,
        ]);
        $send = json_encode($send, JSON_UNESCAPED_UNICODE);
        $this->socket_connector->push($this->fd, $send);

        $fileName     = "充值记录导出";
        $headArr      = $this->getVipColumns();
        $data         = $importData;
        $download_url = xlsxFileLocalStorage($headArr, $data, $fileName, $this->host);
        return Normal::returnWsStatus(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $download_url,
            'name'=>'充值记录导出'
        ]);
    }
    public function getVipColumns() {
        return [
            '店铺',
            '账号',
            '购买天数',
            '支付金额',
            '支付方式',
            '支付时间',
            '支付单号',
            '支付流水号'
        ];
    }
}
